#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

/** http simple wrapper */
/*
 * caller must ensure that dest buffer is enough big.
 * @ret the dest buf length, or -1 if failed.
 */
static int http_pack(unsigned char *dest, unsigned char *src, int len)
{
    if(dest == NULL || src == NULL || len <= 0)
        return -1;
    int dst_len = 0;

    dst_len += sprintf(dest, "HTTP/1.1 200 OK\r\n");
    dst_len += sprintf(dest+dst_len, "Content-Length:%02d\r\n",len);
    dst_len += sprintf(dest+dst_len, "\r\n");
    memcpy(dest+dst_len,src,len);
    dst_len += len;

    return dst_len;
}
static int http_parse(unsigned char *dest, unsigned char *src, int len)
{
    if(dest == NULL || src == NULL)
        return -1;
    int dst_len = 0;
    int fix_len = 0;
    char http_header[64]={0};
	int ret = 0;

    fix_len = strlen("HTTP/1.1 200 OK\r\nContent-Length:99\r\n\r\n");
    if(len <= fix_len)
        return -1;
	printf("fix_len = %d\n",fix_len);
    memcpy(http_header,src, fix_len);
	printf("http_header:%s",http_header);
    ret = sscanf(http_header,"HTTP/1.1 200 OK\r\nContent-Length:%d\r\n\r\n",&dst_len);
    memcpy(dest,src+fix_len,dst_len);

    return dst_len;
}

static void print(char *prefix, unsigned char *buf,int len)
{
	int i = 0;

	printf("%s: ",prefix);
	for(i=0;i<len;i++)
		printf("0x%02x ",buf[i]);
	printf("\n");
}

int main(int argc, char *argv[])
{
	int ret = 0;
	int len = 0;
	char buf[14]={0x40,0x20,0x23,0x12,0x12,0x34,0x12,0x98,0x33,0x00,0x00,0x12,0x34,0x34};
	char dst[100]={0};
	
	print("buf orig",buf,14);
	ret = http_pack(dst,buf,14);
	printf("ret = %d\n",ret);
	
	memset(buf,0,sizeof(buf));
	ret = http_parse(buf,dst,ret);
	printf("ret = %d\n",ret);
	print("buf parse",buf,14);

	return ret;
}

